﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;

namespace CoreLib.MySQL
{
    public class DbProvider
    {
        public string Host;
        public string UserId;
        public string Password;
        public string Database;
        public bool Pooling = false;
        public uint MinPoolCount = 1;
        public uint MaxPoolCount = 100;
        public ConnectionProtocol ConnectionProtocol;
        public uint? Port;
        public string Name;
        public string DbConnectionString { get; private set; }
        public string MySqlConnectionString { get; private set; }

        public MySqlConnection CreateDbConnection()
        {
            if (string.IsNullOrEmpty(MySqlConnectionString))
                CreateConnectionString();
            var conn = new MySqlConnection(this.DbConnectionString);
            conn.Open();
            return conn;
        }

        public MySqlConnection CreateMySqlConnection()
        {
            if (string.IsNullOrEmpty(MySqlConnectionString))
                CreateConnectionString();
            var conn = new MySqlConnection(this.MySqlConnectionString);
            conn.Open();
            return conn;
        }

        private void CreateConnectionString()
        {
            var connectionBuilder = new MySqlConnectionStringBuilder();
            if (!string.IsNullOrEmpty(this.Host))
                connectionBuilder.Server = this.Host;
            connectionBuilder.UserID = this.UserId;
            connectionBuilder.Password = this.Password;
            if (this.Pooling)
            {
                connectionBuilder.Pooling = this.Pooling;
                connectionBuilder.MinimumPoolSize = MinPoolCount;
                connectionBuilder.MaximumPoolSize = MaxPoolCount;
            }
            if (Port != null)
                connectionBuilder.Port = (uint)this.Port;
            switch (ConnectionProtocol)
            {
                case ConnectionProtocol.Pipe:
                    connectionBuilder.ConnectionProtocol = MySqlConnectionProtocol.Pipe;
                    connectionBuilder.PipeName = Name;
                    break;
                case ConnectionProtocol.SharedMemory:
                    connectionBuilder.ConnectionProtocol = MySqlConnectionProtocol.SharedMemory;
                    connectionBuilder.SharedMemoryName = Name;
                    break;
                case ConnectionProtocol.Tcp:
                    connectionBuilder.ConnectionProtocol = MySqlConnectionProtocol.Tcp;
                    break;
            }
            this.MySqlConnectionString = connectionBuilder.ToString();
            connectionBuilder.Database = this.Database;
            this.DbConnectionString = connectionBuilder.ToString();
        }
    }
}
